/** 
 * Copyright (C), 2010-2012, AIYOU Software Co.,Ltd. ALL RIGHTS RESERVED. 
 * File name:RegLoginAction.java
 * Version:1.0
 * Date:Dec 17, 2011
 * Description: 
 * author:whh 
 */
package com.tietiao.action.user;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.tietiao.common.action.BaseAction;
import com.tietiao.common.bean.AreaBean;
import com.tietiao.common.bean.NoticeSetBean;
import com.tietiao.common.constants.SysUserConstants;
import com.tietiao.common.constants.TietiaoConstants;
import com.tietiao.common.json.JsonUtils;
import com.tietiao.common.util.AreaUtil;
import com.tietiao.common.util.ImageUtils;
import com.tietiao.common.util.SendEmailClient;
import com.tietiao.common.util.StringUtil;
import com.tietiao.common.util.TietiaoUtil;
import com.tietiao.dao.model.SearchLableStatistics;
import com.tietiao.dao.model.SysUser;
import com.tietiao.dao.model.UserInvite;
import com.tietiao.service.miduserattention.MidUserAttentionService;
import com.tietiao.service.search.SearchService;
import com.tietiao.service.sysuser.SysUserService;
import com.tietiao.service.userinvite.UserInviteService;

@Controller
@Scope("prototype")
public class UcenterAction extends BaseAction {
	private static final long serialVersionUID = -737414858771525004L;
	@Resource
	private SysUserService sysUserService;
	@Resource
	private MidUserAttentionService midUserAttentionService;
	@Resource
	private UserInviteService userInviteService;
	@Resource
	private SearchService searchService;
	private String email;
	private SysUser userInfo;
	// 上传图片路径
	private File commodityPic;
	private String commodityPicFileName;

	/**
	 * 功能：用户中心跳转首页面（有查询用户信息）
	 * 
	 * @author: whh
	 * @Date: Dec 17, 2011
	 */
	public String index() {
		return DEFAULT;
	}

	public String userInfo() {
		SysUser sysUser = sysUserService.loadSysUserById(getUser().getUserId());
		request.setAttribute("provinces", AreaUtil.getProvince());
		if (sysUser.getProvince() != null && !"".equals(sysUser.getProvince())) {
			request.setAttribute("citys", AreaUtil.getCityByProv(sysUser.getProvince()));
		}
		TietiaoUtil.setToken(request);
		request.setAttribute("userInfo", sysUser);
		return DEFAULT;
	}

	/**
	 * 
	 * 功能：注册成功第一步，批量关注好友
	 * 
	 * @author: whh
	 * @Date: 2012-1-8
	 * 
	 * @return
	 */
	public String stepOne() {
		List<SearchLableStatistics> list = searchService.getSearchLableStatistics();
		request.setAttribute("hotLables", list);
		// 初始化数据
		if (list != null && list.size() != 0) {
			List<String> midUserAttention = midUserAttentionService.selectFriendsUser(getUser().getUserId());
			request.setAttribute("midUserAttention", midUserAttention);

			List<SysUser> sysUsers = sysUserService.selectAttHotLable(list.get(0).getSearchLabel());
			request.setAttribute("sysUsers", sysUsers);
		}
		return dispatcher("/jsp/fg/member/reg_step_one.jsp");
	}

	/**
	 * 
	 * 功能：
	 * 
	 * @author: whh
	 * @Date: 2012-1-8
	 * 
	 * @return
	 */
	public String stepTwo() {
		return dispatcher("/jsp/fg/member/reg_ok.jsp");
	}

	/**
	 * 功能：喜欢热门标签的用户
	 * 
	 * @author: whh
	 * @Date: 2012-1-8
	 * @return
	 */
	public String likeLableUser() {
		List<String> midUserAttention = midUserAttentionService.selectFriendsUser(getUser().getUserId());
		request.setAttribute("midUserAttention", midUserAttention);
		List<SysUser> sysUsers = sysUserService.selectAttHotLable(request.getParameter("lableName"));
		request.setAttribute("sysUsers", sysUsers);
		return dispatcher("/jsp/fg/member/user_atten.jsp");
	}

	/**
	 * 
	 * 功能：上传图片
	 * 
	 * @Date: 2011-12-14
	 * @return
	 */
	public String upload() throws Exception {
		response.setContentType("text/html");
		SysUser sysUser = getUser();
		JSONObject obj = new JSONObject();
		obj.put("flag", false);
		if (commodityPic == null || !StringUtil.checkStrIsNotNull(commodityPicFileName)) {
			obj.put("errorCode", 0);
			obj.put("errorMsg", "您尚未选择图片!请重试");
		}
		try {
			Integer checkFlag = checkUploadFiles(commodityPic, commodityPicFileName);
			if (checkFlag == 1) {
				String picName = "/head/head_" + sysUser.getUserId() + commodityPicFileName.substring(commodityPicFileName.indexOf("."));
				String picPath = TietiaoConstants.PIC_ROOT_PATH + picName;
				ImageUtils.convert(TietiaoConstants.RESULT_USER_PHOTO_H, TietiaoConstants.RESULT_USER_PHOTO_W, commodityPic, new File(picPath));
				String imgPath = TietiaoConstants.SERVICE_ROOT_PATH + picName;
				obj.put("flag", true);
				obj.put("imgRelPath", imgPath);
				sysUser.setUserPhoto(picName);
				sysUserService.updateSysUser(sysUser);
			} else {
				obj.put("errorCode", checkFlag);
			}
		} catch (Exception e) {
			obj.put("errorCode", 0);
			obj.put("errorMsg", "上传图片出现异常，请重试!");
			e.printStackTrace();
		}
		response.getWriter().append(obj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		System.out.println(obj.toString());
		return null;
	}

	/**
	 * 功能：修改用户资料
	 * 
	 * @author: whh
	 * @Date: 2012-1-8
	 * @return
	 */
	public String update() {
		SysUser sysUser = getUser();
		if (TietiaoUtil.isToken(request)) {

			// 数据库中是否存非当前用户的邮箱
			SysUser loadUser = null;
			if (userInfo.getEmail() != null && !userInfo.getEmail().equals(sysUser.getEmail())) {
				loadUser = sysUserService.loadSysUserByCodeOrEmail(userInfo.getEmail());
			}
			if (loadUser == null) {
				sysUser = sysUserService.loadSysUserById(sysUser.getUserId());
				sysUser.setEmail(userInfo.getEmail());
				sysUser.setRelName(userInfo.getRelName());
				sysUser.setGender(userInfo.getGender());
				sysUser.setBirthDay(userInfo.getBirthDay());
				sysUser.setProvince(userInfo.getProvince());
				sysUser.setCity(userInfo.getCity());
				sysUser.setSchool(userInfo.getSchool());
				sysUser.setHomePage(userInfo.getHomePage());
				sysUser.setSignature(userInfo.getSignature());
				if (sysUser.getUserPhoto().endsWith(SysUserConstants.HEAD_UNKNOW) || sysUser.getUserPhoto().endsWith(SysUserConstants.HEAD_MAN) || sysUser.getUserPhoto().endsWith(SysUserConstants.HEAD_WOMAN)) {
					if (sysUser.getGender() == SysUserConstants.GENDER_UNKNOW) {
						sysUser.setUserPhoto("/head/" + SysUserConstants.HEAD_UNKNOW);
					} else if (sysUser.getGender() == SysUserConstants.GENDER_MAN) {
						sysUser.setUserPhoto("/head/" + SysUserConstants.HEAD_MAN);
					} else {
						sysUser.setUserPhoto("/head/" + SysUserConstants.HEAD_WOMAN);
					}
				}
				sysUserService.updateSysUser(sysUser);
				request.setAttribute("result", true);
			} else {
				request.setAttribute("result", false);
				request.setAttribute("message", "邮箱已被占用");
			}
		}
		return dispatcher("ucenter_ucenter_userInfo.htm");
	}

	public String modifyPassInput() {
		TietiaoUtil.setToken(request);
		return DEFAULT;
	}

	/**
	 * 
	 * 功能：修改密码
	 * 
	 * @author: whh
	 * @Date: 2011-12-25
	 */
	public String modifyPass() {
		SysUser sysUser = getUser();
		if (TietiaoUtil.isToken(request)) {
			if (sysUser.getPassword().equals(request.getParameter("oldPass"))) {
				sysUser.setPassword(request.getParameter("password"));
				sysUserService.updateSysUser(sysUser);
				request.setAttribute("result", true);
			} else {
				request.setAttribute("result", false);
				request.setAttribute("message", "原始密码错误！");
			}
		}
		return dispatcher("ucenter_ucenter_modifyPassInput.htm");
	}

	/**
	 * 
	 * 功能：设置消息提醒输入界面
	 * 
	 * @author: TT_LOVE
	 * @Date: 2012-6-10
	 * 
	 * @return
	 */
	public String toSetNotice() {
		SysUser sysUser = getUser();
		TietiaoUtil.setToken(request);
		request.setAttribute("notice", sysUser.getNoticeSetBean());
		return DEFAULT;
	}

	/**
	 * 
	 * 功能：保存提醒消息
	 * 
	 * @author: TT_LOVE
	 * @Date: 2012-6-10
	 * 
	 * @return
	 */
	public String setNotice() {
		SysUser sysUser = getUser();
		NoticeSetBean bean = sysUser.getNoticeSetBean();
		String type = request.getParameter("type");
		String result = request.getParameter("result");
		if ("sysNotice".equals(type)) {
			bean.setSysNotice(Boolean.valueOf(result));
		} else if ("reCommendNotice".equals(type)) {
			bean.setReCommendNotice(Boolean.valueOf(result));
		} else if ("attentionMeNotice".equals(type)) {
			bean.setAttentionMeNotice(Boolean.valueOf(result));
		} else if ("commentNotice".equals(type)) {
			bean.setCommentNotice(Boolean.valueOf(result));
		}
		sysUser.setColumn3(JsonUtils.getJsonString4JavaPOJO(bean));
		sysUserService.updateSysUser(sysUser);
		request.setAttribute("result", true);
		return dispatcher("ucenter_ucenter_toSetNotice.htm");
	}

	/**
	 * 
	 * 功能：获得邀请界面
	 * 
	 * @author: whh
	 * @Date: 2011-12-18
	 * @return
	 */
	public String inviteInput() {
		TietiaoUtil.setToken(request);
		return DEFAULT;
	}

	/**
	 * 
	 * 功能：邀请结果
	 * 
	 * @author: whh
	 * @Date: 2011-12-18
	 * @return
	 */
	public String invite() {
		if (TietiaoUtil.isToken(request)) {
			SysUser sysUser = getUser();
			String inviteCode = TietiaoUtil.getInviteCode();
			Map<String, Object> para = new HashMap<String, Object>();
			para.put("inviteCode", inviteCode);
			para.put("userName", StringUtil.strIsNull(sysUser.getRelName()) ? sysUser.getPetName() : sysUser.getRelName());
			boolean result = SendEmailClient.sendInvite(email, para);
			if (result) {
				UserInvite userInvite = new UserInvite();
				userInvite.setInviteCode(inviteCode);
				userInvite.setInviteTime(new Date());
				userInvite.setInviteUserId(0);
				userInvite.setIsInvaild(0);
				userInvite.setUserId(sysUser.getUserId());
				userInvite.setWasInviteEmail(email);
				userInvite.setWasInviteTell(null);
				userInviteService.insertUserInvite(userInvite);
			}
			request.setAttribute("result", result);
		}
		return dispatcher("ucenter_ucenter_inviteInput.htm");
	}

	/**
	 * 功能：检查上传的文件是否符合限制条件
	 * 
	 * @author: zhijian.zhang
	 * @Date: 2011-12-14
	 * @param file
	 *            要上传的文件
	 * @param fileName
	 *            文件名称
	 * @return 1：符合条件 -1：图片大小太大 -2：图片格式不符合限制条件 -3：分辨率不对
	 */
	private Integer checkUploadFiles(File file, String fileName) throws IOException {
		String fileType = fileName.substring(fileName.indexOf(".")).toLowerCase();
		if (TietiaoConstants.PHOTO_ALL0W_FILE.contains(fileType.toLowerCase())) {
			if (file.length() <= TietiaoConstants.PHOTO_ALL0W_MAX_SIZE) {
				FileInputStream fis = new FileInputStream(file);
				BufferedImage bufferedImg = ImageIO.read(fis);
				int imgWidth = bufferedImg.getWidth();
				int imgHeight = bufferedImg.getHeight();
				if (imgWidth >= TietiaoConstants.PHOTO_ALLOW_MIN_W && imgHeight >= TietiaoConstants.PHOTO_ALLOW_MIN_H && imgWidth <= TietiaoConstants.PHOTO_ALLOW_MAX_W && imgHeight <= TietiaoConstants.PHOTO_ALLOW_MAX_H) {
					return 1;
				} else {
					return -3;
				}
			} else {
				return -1;
			}
		} else {
			return -2;
		}
	}

	/**
	 * 功能：异步获得二级城市
	 * 
	 * @Date: 2011-12-14
	 * @return
	 */
	public void searchCity() throws Exception {
		response.setContentType("text/html");
		JSONArray array = new JSONArray();
		List<AreaBean> list = AreaUtil.getCity(request.getParameter("proviCode"));
		for (AreaBean areaBean : list) {
			JSONObject obj = new JSONObject();
			obj.put("code", areaBean.getAreaCode());
			obj.put("name", areaBean.getAreaName());
			array.add(obj);
		}
		response.getWriter().append(array.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public SysUser getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(SysUser userInfo) {
		this.userInfo = userInfo;
	}

	public File getCommodityPic() {
		return commodityPic;
	}

	public void setCommodityPic(File commodityPic) {
		this.commodityPic = commodityPic;
	}

	public String getCommodityPicFileName() {
		return commodityPicFileName;
	}

	public void setCommodityPicFileName(String commodityPicFileName) {
		this.commodityPicFileName = commodityPicFileName;
	}
}
